import random
import threading
import time
import matplotlib
from matplotlib import pyplot as plt
from matplotlib import font_manager
import pymysql

class mat():
    def __init__(self, x, y, y2=None):
        self.x = x
        self.y = y
        self.y2 = y2
        self.plt = plt

    def socSQL(self):
        self.conn = pymysql.connect(host='localhost', port=3306, db='soc9527', user='root', password='root', charset='utf8')
        self.cur = self.conn.cursor()
        sql = 'select * from soc'
        count = self.cur.execute(sql)
        ret = self.cur.fetchall()
        self.cur.close()
        self.conn.close()
        time.sleep(3)

        idlist = []
        rSocLlist = []
        rSocRlist = []
        rSocBlist = []
        for i in ret:
            idlist.append(i[0])
            rSocLlist.append(i[1])
            rSocRlist.append(i[2])
            rSocBlist.append(i[3])
        return {'id': idlist, 'rSocL': rSocLlist, 'rSocR': rSocRlist, 'rSocB': rSocBlist}

    def set_font(self, figsizeW=14, figsizeH=7, size=18, grid=False):
        '''
        设置中文
        :param figsizeW: 字体宽
        :param figsizeH: 字体高
        :param size: 字体大小
        :param grid:
        :return:
        '''
        self.my_font = font_manager.FontProperties(fname=r"C:\Windows\Fonts\simsun.ttc", size=size)
        matplotlib.rc('figure', figsize=(figsizeW, figsizeH))
        self.plt.rc('font', size=size)
        self.plt.rc('axes', grid=grid)
        #设置字体为楷体
        self.plt.rcParams['font.sans-serif'] = ['KaiTi']

    def SetChartSIZE(self, whidh=20, high=15, dpi=80):
        '''
        设置画布大小
        :param whidh: 宽
        :param high: 高
        :param dpi: 每行显示的像素 图片清晰度
        :return:
        '''
        self.plt.figure(figsize=(whidh, high), dpi=dpi)

    def SetXticks(self, sizeNum=2, stepSize=3, ShowStr=False, rotation=45):
        '''
        :param sizeNum: 计算步长参数
        :param stepSize: 补偿切片
        :param rotation: 字体旋转 角度
        :return: 参数为0 默认传入参数 x 轴
        '''
        if ShowStr:
            _x = list(x)
            xtick_labels = ["你好.{}".format(i) for i in _x]
            self.plt.xticks(_x, xtick_labels, rotation=rotation)
        else:
            if sizeNum:
                xtick_labels = [i/sizeNum for i in range(4, 49)]
            else:
                xtick_labels = self.x
            if stepSize:
                self.plt.xticks(xtick_labels[::stepSize])
            else:
                self.plt.xticks(xtick_labels)

    def SetYticks(self, sizeNum=0, minZero=False):
        '''
        :param sizeNum: Y轴末端加补偿
        :param minZero: Y轴是否从0开始
        :return:
        '''
        if minZero: minNum=0
        else: minNum = min(y)
        if sizeNum:
            self.plt.yticks(range(minNum, max(y) + sizeNum))
        else:
            self.plt.yticks(range(minNum, max(y) + 1))

    def DrotationInfo(self, xlabel="时间", ylabel="温度", title="温度"):
        '''
        添加描述信息
        :param xlabel: 标签
        :param ylabel: 标签
        :param title:  标题
        :return:
        '''
        self.plt.xlabel(xlabel)
        self.plt.ylabel(ylabel)
        self.plt.title(title)

    def DrawChart(self, Drawtype="plot", savefig=False, savePath=r't2.png', grid=True, alpha=1.0, label1="深圳", label2="广西", lengend=True):
        '''
        :param Drawtype: 画折线图, 散点图等图类型
        :param savefig: 保存图片
        :param savePath: 保存图片路径
        :param grid: 绘制网格
        :param alpha: 透明度 1 透明, 越小, 透明度越高
        :param label1: 图例标注
        :param lengend: 图例
        :return:
        '''
        # label=图例名, color=线条颜色, linestyle=线条样式, linewidth=线条粗细, alpha=线条透明度
        if Drawtype == "plot":      # 折线
            self.plt.plot(self.x, self.y, label=label1, color="orange", linestyle='-', linewidth=5, alpha=0.5)
            self.plt.plot(self.x, self.y2, label=label2, color="cyan", linestyle="-", linewidth=5, alpha=0.5)
        elif Drawtype == "scatter":      #散点
            self.plt.scatter(self.x, self.y2, label=label2, color="cyan", linestyle="-", linewidth=5, alpha=0.5)
        elif Drawtype == "bar":        # 条形
            self.x = ["战狼2", "速度与激情8", "功夫瑜伽", "西游伏妖篇", "变形金刚5：最后的骑士", "摔跤吧！爸爸", "加勒比海盗5：死无对证", "金刚：骷髅岛", "极限特工：终极回归",
                 "生化危机6：终章", "乘风破浪", "神偷奶爸3", "智取威虎山", "大闹天竺", "金刚狼3：殊死一战", "蜘蛛侠：英雄归来", "悟空传", "银河护卫队2", "情圣", "新木乃伊", ]

            self.y = [56.01, 26.94, 17.53, 16.49, 15.45, 12.96, 11.8, 11.61, 11.28, 11.12, 10.49, 10.3, 8.75, 7.55, 7.32,
                 6.99, 6.88, 6.86, 6.58, 6.23]
            self.plt.bar(range(len(self.x)), self.y, label=label2, color="cyan", linestyle="-", linewidth=5, alpha=0.5)
            self.plt.xticks(range(len(self.x)), self.x, rotation=90)
        elif Drawtype=="barh":    # 横的条形图
            self.x = ["战狼2", "速度与激情8", "功夫瑜伽", "西游伏妖篇", "变形金刚5：最后的骑士", "摔跤吧！爸爸", "加勒比海盗5：死无对证", "金刚：骷髅岛", "极限特工：终极回归",
                 "生化危机6：终章", "乘风破浪", "神偷奶爸3", "智取威虎山", "大闹天竺", "金刚狼3：殊死一战", "蜘蛛侠：英雄归来", "悟空传", "银河护卫队2", "情圣", "新木乃伊", ]

            self.y = [56.01, 26.94, 17.53, 16.49, 15.45, 12.96, 11.8, 11.61, 11.28, 11.12, 10.49, 10.3, 8.75, 7.55, 7.32,
                 6.99, 6.88, 6.86, 6.58, 6.23]
            # 控制线条高低
            self.plt.barh(range(len(self.x)), self.y, label=label2, color="cyan", linestyle="-", linewidth=0.5, alpha=0.5, height=0.3)
            self.plt.yticks(range(len(self.x)), self.x)
        elif Drawtype=="maxBar":        # 绘制多次条形图
            a = ["猩球崛起3：终极之战", "敦刻尔克", "蜘蛛侠：英雄归来", "战狼2"]
            b_16 = [15746, 312, 4497, 319]
            b_15 = [12357, 156, 2045, 168]
            b_14 = [2358, 399, 2358, 362]
            bar_width = 0.2

            x_14 = list(range(len(a)))
            x_15 = [i + bar_width for i in x_14]
            x_16 = [i + bar_width * 2 for i in x_14]

            plt.bar(range(len(a)), b_14, width=bar_width, label="9月14日")
            plt.bar(x_15, b_15, width=bar_width, label="9月15日")
            plt.bar(x_16, b_16, width=bar_width, label="9月16日")

            # 设置图例
            plt.legend()

            # 设置x轴的刻度
            plt.xticks(x_15, a)

            plt.show()
            return

        elif Drawtype=="hist":    # 直方图
            a = [131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127,
                 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138, 117, 111, 78, 132, 124,
                 113, 150, 110, 117, 86, 95, 144, 105, 126, 130, 126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101,
                 99, 136, 123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127, 105, 120, 107, 129, 116, 108,
                 132, 103, 136, 118, 102, 120, 114, 105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,
                 156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102, 123, 107, 143, 115, 136, 118, 139, 123, 112,
                 118, 125, 109, 119, 133, 112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135, 115, 146,
                 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154, 136, 100, 118, 119, 133, 134, 106, 129, 126, 110,
                 111, 109, 141, 120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126, 114, 140, 103, 130,
                 141, 117, 106, 114, 121, 114, 133, 137, 92, 121, 112, 146, 97, 137, 105, 98, 117, 112, 81, 97, 139,
                 113, 134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110, 105, 129, 137, 112, 120, 113,
                 133, 112, 83, 94, 146, 133, 101, 131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111, 111,
                 133, 150]

            # 计算组数
            d = 3  # 组距
            num_bins = (max(a) - min(a)) // d
            print(max(a), min(a), max(a) - min(a))
            print(num_bins)

            plt.hist(a, num_bins)
            # 设置x轴的刻度
            plt.xticks(range(min(a), max(a) + d, d))

            plt.grid()

            plt.show()
            return

        elif Drawtype=="echarts":
            import seaborn as sns
            sns.set_theme(style="ticks")

            # 加载安斯科姆四重奏的示例数据集
            df = sns.load_dataset("anscombe")

            # Show the results of a linear regression within each dataset
            sns.lmplot(x="x", y="y", col="dataset", hue="dataset", data=df,
                       col_wrap=2, ci=None, palette="muted", height=4,
                       scatter_kws={"s": 50, "alpha": 1})
            return

        if savefig:
            self.plt.savefig(savePath)
        if grid:
            self.plt.grid(alpha=alpha)
        if lengend:
            self.plt.legend(loc="upper left")    # loc: 图例位置
        self.plt.show()

    def Func(self):
        while True:
            ret = self.socSQL()
            print(ret['rSocL'])
            x = [i for i in ret['id']]
            y = [int(i) for i in ret['rSocL']]
            plt.ion()
            plt.cla()
            plt.plot(x, y, 'ro--')
            plt.pause(0.1)
            time.sleep(3)
            plt.close()


if __name__ == '__main__':
    x = [i for i in range(2, 26, 2)]
    y = [15, 13, 14, 5, 17, 20, 25, 26, 26, 27, 22, 18]
    y2 = [5, 8, 10, 12, 14, 18, 22, 19, 16, 12, 9, 2]

    Draw_obj = mat(x, y, y2)
    t = threading.Thread(target=Draw_obj.Func)
    t.start()
    plt.show()


    # ret = Draw_obj.socSQL()
    # print(ret)
    #
    # Draw_obj.set_font()
    # Draw_obj.SetChartSIZE(whidh=15)
    # Draw_obj.SetXticks(stepSize=5, ShowStr=True)
    # Draw_obj.SetYticks()
    # Draw_obj.DrotationInfo()
    # Draw_obj.DrawChart(Drawtype="echarts", savefig=False, alpha=0.4)
